//
//  PictureSelectorViewController.swift
//  Weibo
//
//  Created by 冯童童 on 16/1/23.
//  Copyright © 2016年 冯童童. All rights reserved.
//

import UIKit
import SnapKit

private let PictureSelectorCellId = "PictureSelectorCellId"
private let selectorCellMargin : CGFloat = 5
private let rowCount : CGFloat = 4
private let maxImageCount = 9
class PictureSelectorViewController: UICollectionViewController {

   lazy var imageList = [UIImage]()
    
    
    init() {
        let w = (KWidth - (rowCount + 1) * selectorCellMargin) / rowCount
        
      let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: w, height: w)
        layout.minimumInteritemSpacing = selectorCellMargin
        layout.minimumLineSpacing = selectorCellMargin
        layout.sectionInset = UIEdgeInsetsMake(selectorCellMargin, selectorCellMargin, 0, selectorCellMargin)
        super.init(collectionViewLayout: layout)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

              self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: PictureSelectorCellId)


    }

}

extension PictureSelectorViewController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = imageList.count == maxImageCount ? 0 : 1
        return imageList.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureSelectorCellId, forIndexPath:indexPath ) as! PictureSelectorCell
        
        if indexPath.item == imageList.count {
            print(indexPath.item, imageList.count)
            cell.image = nil
        }else{
            cell.image = imageList[indexPath.item]
            
        }
       // cell.backgroundColor = UIColor.randomColor()
        cell.selectorDelegate = self
        return cell
    }
}


extension PictureSelectorViewController : PictureSelectorCellDelegate{
    func userWillSelectPicture(cell : PictureSelectorCell) {
        if cell.image != nil {
            print("已经设置图片了")
            return
        }
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.allowsEditing = true
        presentViewController(picker, animated: true, completion: nil)
        
    }
    
    func userWillDeletePicture(cell : PictureSelectorCell) {
        if let indexPath  = collectionView?.indexPathForCell(cell) {
            imageList.removeAtIndex(indexPath.item)
            collectionView?.reloadData()
        }
        
    }
}

extension PictureSelectorViewController : UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(image)
        print("------------")
        print(editingInfo)
        
        imageList.append(image)
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}

protocol PictureSelectorCellDelegate : NSObjectProtocol {
    
    func userWillSelectPicture(cell : PictureSelectorCell)
    func userWillDeletePicture(cell : PictureSelectorCell)
}

class PictureSelectorCell : UICollectionViewCell {
    
    weak var selectorDelegate : PictureSelectorCellDelegate?
    
    var image : UIImage? {
        didSet{
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    @objc private func addBtnDidClick() {
        selectorDelegate?.userWillSelectPicture(self)
        
    }
    
    @objc private func deleteBtnDidClick() {
        selectorDelegate?.userWillDeletePicture(self)
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(addBtn.snp_top)
            make.right.equalTo(addBtn.snp_right)
            
        }
        
        addBtn.imageView?.contentMode = .ScaleAspectFill
        
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
    }
    
    
    private lazy var addBtn : UIButton = UIButton(imageName: nil, backImageName: "compose_pic_add")
     private lazy var deleteBtn : UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
    
}
